# -*- coding:utf-8 -*-
"""
@Time : 2021/1/23 22:10
@Author: langengel
@Des: 微信服务器推送
"""

import time
from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException
from wechatpy.utils import check_signature
from wechatpy import parse_message, create_reply
from wechatpy.replies import EmptyReply
from fastapi import Request
from fastapi.responses import Response
from config.wechat import TOKEN, EN_COD_IN_AES_KEY, APP_ID
from wechatpy.crypto import WeChatCrypto


async def server_check(
        signature: str,
        timestamp: str,
        nonce: str,
        echostr: str = None,
):
    """
    微信服务器验证接口
    """
    try:
        check_signature(TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        return "error"
    return Response(echostr)
    # 处理异常情况或忽略


async def wechat_listen(
        req: Request,
        signature: str,
        timestamp: str,
        nonce: str,
        msg_signature: str,
        openid: str = None,
):
    """
    微信服务器推送接口 加密模式
    """
    # 签名验证
    try:

        check_signature(TOKEN, signature, timestamp, nonce)

    except InvalidSignatureException:
        print(openid)
        return "check_signature error"

    # xml消息解密
    crypto = WeChatCrypto(token=TOKEN, encoding_aes_key=EN_COD_IN_AES_KEY, app_id=APP_ID)
    try:
        decrypted_xml = crypto.decrypt_message(
            msg=await req.body(),
            signature=msg_signature,
            timestamp=timestamp,
            nonce=nonce
        )

    except (InvalidAppIdException, InvalidSignatureException):

        return "decrypt_message error"

    # xml消息解析
    msg = parse_message(decrypted_xml)
    # print(msg)
    # 监听事件
    if msg.type == "event":
        print("event:", msg.event)
        # 空回复
        reply = EmptyReply()
        if msg.event == "unsubscribe":
            # 取消关注事件
            print(f"{msg.source}->取消关注")

        if msg.event == "subscribe":
            # 公众号关注事件
            print(f"{msg.source}->已关注")
            reply = create_reply('谢谢你勒关注[LetMeSee]', msg)
        if msg.event == "location":
            # print("地理位置纬度", msg.latitude)
            # print("地理位置经度", msg.longitude)
            # print("地理位置精度", msg.precision)
            reply = create_reply(f"你当前的位置：经度：{msg.latitude} 纬度：{msg.longitude} 精度：{msg.precision}", msg)
            # 上报地理位置事件
            pass

        response = Response(
            crypto.encrypt_message(
                msg=reply.render(),
                nonce=nonce,
                timestamp=timestamp
            ),
            media_type="application/xml")
        return response

    # 消息事件
    if msg.type == 'text':
        content = str(msg.content)
        if content == '【收到不支持的消息类型，暂无法显示】':
            reply = create_reply('你发这个是什么鬼？ /::!', msg)

        elif "天气" in content:
            reply = create_reply('天是蓝色的，水是清澈的，我是爱你的/:heart', msg)

        elif "有时间吗" in content:
            reply = create_reply('今天没有时间呢', msg)

        elif "时间" in content:
            reply = create_reply('现在是北京时间:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), msg)

        else:
            reply = create_reply(content, msg)

    elif msg.type == 'image':
        reply = create_reply('这是条图片消息', msg)

    elif msg.type == 'voice':
        reply = create_reply('这是条语音消息', msg)

    elif msg.type == "location":
        reply = create_reply('这是条位置消息', msg)

    else:
        reply = create_reply('这是条其他类型消息', msg)

    response = Response(
        crypto.encrypt_message(
            msg=reply.render(),
            nonce=nonce,
            timestamp=timestamp
        ),
        media_type="application/xml"
    )
    return response
